<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class News extends MY_Luckydog
{
	public function __construct()
	{
		parent::__construct();
        
        $this->load->model('luckydog/News_model', 'news');
        $this->load->model('luckydog/Newscategory_model', 'cat');
        $this->load->model('luckydog/Address_model', 'address');
	}

/**
 * 新闻列表
 * @return [type] [description]
 */
    public function index(){
        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $keyword = $this->input->get('keyword') ? $this->input->get('keyword') : '';
        $endtime = $this->input->get('endtime') ? $this->input->get('endtime') : 0;
        $starttime = $this->input->get('starttime') ? $this->input->get('starttime') : 0;
        $cat_id = $this->input->get('cat_id') ? $this->input->get('cat_id') : 0;
        $isruanwen = $this->input->get('isruanwen');
        $readonly = $this->input->get('readonly');
        $_SESSION['v_menu'] = 'news';
        $filter = array("cat_id"=>$cat_id,'keyword'=>$keyword,'endtime'=>strtotime($endtime),'starttime'=>strtotime($starttime),'isruanwen'=>($isruanwen),'readonly'=>($readonly));
        $limit = 20;
        $total_rows = $this->news->getNewsCnt($filter);
        $base_url = '/luckydog/news/index?';
        $page_links = $this->create_page_links($base_url,$total_rows,$limit);
        $newsList = $this->news->getNewsList($filter,$per_page, $limit);
        foreach ($newsList as $key => $value) {
            $catDetail = $this->cat->get_cat_by_id($value['categoryid']);
            $newsList[$key]['cat_name'] = $catDetail['cat_name'];
			if($value['isruanwen'])
			{
				$totalMoneyByNewsID = $this->news->getTotalMoneyByNewsID($value['newsID']);
				$newsList[$key]['surplus'] = $value['totalmoney']-$totalMoneyByNewsID;
			}
        }
        $catList = $this->cat->get_cat_list();
        $data = array(
            'newsList'=>$newsList,
            'page_links'=>$page_links,
            'per_page'=>$per_page,
            'total_rows'=>$total_rows,
            'catList'=>$catList,
            'cat_id'=>$cat_id,
            'keyword'=>$keyword,
            'starttime'=>$starttime,
            'endtime'=>$endtime,
            'isruanwen'=>$isruanwen,
            'readonly'=>$readonly
            );
        $this->load->view("/luckydog/news/index", $data);
    }

    public function textures()
    {
        
        $id = $this->input->get("id",true)?$this->input->get("id",true):"";
        $catList = $this->cat->get_cat_list();
        $_SESSION['v_menu'] = 'news';
        $data = array();
        $point = $points = $this->setPoint(3);

        
        if(!empty($id)){
            $newsInfo = $this->news->getNewsInfobyID($id);
            $newsInfo['point'] ? $newsInfo['point'] : $point;
            if($newsInfo['region'])
            {
                $region = explode(",",$newsInfo['region']);
                $newsInfo['provinceid'] = $region[0];
                $newsInfo['cityid'] = $region[1];
            }
            $data["NewsInfo"] = $newsInfo;
        }else{
            $data["NewsInfo"]['point'] = $point;
        }

        $this->load->model("address_model","address");
        $fields = " id, name ";
        //基本信息
        $provinceList = array();
        $provinceList = $this->address->getProvinceList($fields);
        $provinceId = $newsInfo['provinceid']?$newsInfo['provinceid']:110000;
        $cityList = array();
        $cityList = $this->address->getCityList($provinceId, $fields);

        // print_R($provinceList);

        $data['catList'] = $catList;
        $data['provinceList'] = $provinceList;
        $data['cityList'] = $cityList;
    	$this->load->view("/luckydog/news/textures", $data);
    }

     public function cityList(){
        $privinceid = $this->input->post("privinceid",true) ? $this->input->post("privinceid",true) : 110000;
        
        $cityList = array();
        $fields = " id, name ";
        //基本信息
        $cityList = $this->address->getCityList($privinceid, $fields);
        echo json_encode($cityList);
        exit();
    }



    //编辑新闻
    public function editNews(){
        $id = $this->input->post("id",true) ? $this->input->post("id",true) : 0;
        $content = $this->input->post("contents") ? $this->input->post("contents") : "";
        $title = $this->input->post("title",true) ? $this->input->post("title",true) : "";
        $point = $this->input->post("point",true) ? $this->input->post("point",true) : $this->config->item("point");;
        $transferfrom = $this->input->post("transferfrom",true) ? $this->input->post("transferfrom",true) : "";
        $cover = $this->input->post("cover",true) ? $this->input->post("cover",true) : "";
        $readonly = $this->input->post("readonly",true) ? $this->input->post("readonly",true) : "";
        $categoryid = $this->input->post("categoryid",true) ? $this->input->post("categoryid",true) : "";
        $provinceid = $this->input->post("provinceid",true) ? $this->input->post("provinceid",true) : "";
        $cityid = $this->input->post("cityid",true) ? $this->input->post("cityid",true) : "";
        $ruanwen = $this->input->post("ruanwen",true) ? $this->input->post("ruanwen",true) : "";
		$totalmoney = $this->input->post("totalmoney",true) ? $this->input->post("totalmoney",true) : 0;

        $data = array(
            "content"=>$content ,
            "title"=>$title ,
            "transferfrom"=>$transferfrom,
            "cover"=>$cover,
            "categoryid"=>$categoryid,
            'point'=>$point,
            'readonly'=>$readonly,
            'region'=>$provinceid?($provinceid.",".$cityid):'',
            'isruanwen'=>$ruanwen,
			'totalmoney'=>$totalmoney,
        );
        if(empty($id)){
            $data['addtime']=time();
        }
        $res = $this->news->editNews($id,$data);
        echo $res;
    }


    //编辑上线下，删除状态
    public function delNews(){
        $id = $this->input->post("id",true) ? $this->input->post("id",true) : 0;
        $res =$this->news->delNews($id);
        echo $res;
    }


    public function upload_cover()
    {
        $this->load->library('Upload');
        $upload = new Upload();
        $file_name =$upload->execute($_FILES['Filedata']);

        $savepath='./upload/news/'.date('Y-m-d').'/';
        $upload->set_upload_dir($savepath);
        if (!file_exists($savepath)){
            mkdir($savepath);
        }
        if(is_string($file_name))
        {
            $res=json_encode(array('code'=>1,'type'=>0,'file_name'=>$file_name));

            echo $res;
        }
        else
        {
            echo json_encode(array('code'=>-1));
        }
    }

    //编辑上线下，删除状态
    public function editStatus(){
        $newsID = $this->input->post("newsID",true) ? $this->input->post("newsID",true) : 0;
        $onlinestatus = $this->input->post("onlinestatus",true) ? $this->input->post("onlinestatus",true) : "";
        $data = array(
            "newsID"=>$newsID,
            "onlinestatus"=>$onlinestatus,
        );
        $res =$this->news->editStatus($data);
        echo $res;
    }

    public function toupload()
    {
        $ossconfig=$this->config->item("oss");
        $id= $ossconfig['id'];
        $key= $ossconfig['key'];
        $host = $ossconfig['host'];
        $callbackUrl = $ossconfig['callbackUrl'];

        $callback_param = array('callbackUrl'=>$callbackUrl, 
                     'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}', 
                     'callbackBodyType'=>"application/json");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);
        $date = date("Y-M-D",time());
        $dir = 'app_news/'.date("Y-m-d",time()).'/';
        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition; 

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start; 


        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        //echo json_encode($arr);
        //return;
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;
        echo json_encode($response);
    }

    function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }


}
/* End of file index.php */
/* Location: ./application/controllers/luckydog/index.php */
